<template>
    <!--    ref="ruleForm" （判断form表单的name属性formName）-->
    <!-- 这三个属性必须有   :model 数据绑定     :rules校验规则   ref给表单设置名字（在click事件中需要去使用）-->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="图书编号">
            <el-input v-model="ruleForm.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="图书名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <!--        prop绑定校验规则-->
        <el-form-item label="作者" prop="author">
            <el-input v-model="ruleForm.author"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    export default {
        data() {
            return {
                ruleForm: {
                    id:'',
                    name: '',
                    author: '',

                },
                //校验规则
                rules: {
                    name: [
                        {required: true, message: '图书不能为空', trigger: 'blur'}
                    ],
                    author: [
                        {required: true, message: '作者不能为空', trigger: 'change'}
                    ]
                }
            };
        },
        methods: {

            submitForm(formName) {
                //_this 表示当前vue对象
                const _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //在这里拿到写好的数据 ruleForm
                        //then:回调    function匿名函数
                        axios.post('http://localhost:8181/book/savebook', this.ruleForm).then(function (resp) {
                            if (resp.data == 'success') {
                                // _this.$message('添加成功！')
                                _this.$router.push('/BookManage')  //跳到图书管理页面
                            }

                        })

                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                //让所有选项置空
                this.$refs[formName].resetFields();
            }
        }, created() {
            //接收到参数 $route
            // alert(this.$route.query.id)
            const _this = this
            //将后端接口中的数据取出来
            axios.get("http://localhost:8181/book/findById/" + this.$route.query.id).then(function (resp) {
                //将返回的数据和ruleForm绑定
                _this.ruleForm = resp.data

            })
        }
    }
</script>
